package com.hula.onion.book.server.spider.platforms.etongdai;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hula.onion.book.server.common.CommonResponse;
import com.hula.onion.book.server.common.LoginForm;
import com.hula.onion.book.server.config.ResponseStatusEnum;
import com.hula.onion.book.server.model.AccountInfo;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by work on 2018/3/20.
 */
@Component
public class ETongDaiSpiderHelper {
    /**
     * 组装请求参数
     *
     * @param form
     * @return
     */
    public Map<String, Object> installRequestParams(LoginForm form) {
        Map<String, Object> map = new HashMap<>(4);
        map.put("loginName", form.getUserName());
        map.put("password", form.getPassword());
        map.put("check", "off");
        map.put("next", "null");
        return map;
    }

    /**
     * 解析账户余额
     *
     * @param json
     * @return
     */
    public CommonResponse parseAccountBalance(String json) {

        try {
            JSONObject accountJson = JSON.parseObject(json);
            if (accountJson.getBoolean("success")) {
                BigDecimal totalInterest = accountJson.getJSONObject("body").
                        getJSONObject("claimMdl").getBigDecimal("totalRevenue");
                //可用金额
                BigDecimal praValidSum = accountJson.getJSONObject("body").
                        getBigDecimal("praValidSum");
                //待收金额
                BigDecimal exaDueInSum = accountJson.getJSONObject("body")
                        .getBigDecimal("exaDueInSum");
                //冻结金额
                BigDecimal praFreezeSum = accountJson.getJSONObject("body")
                        .getBigDecimal("praFreezeSum");
                //可用金额+待收总额+冻结资金
                BigDecimal amount = praValidSum.add(exaDueInSum).add(praFreezeSum);
                BigDecimal waitInterest = accountJson.getJSONObject("body")
                        .getJSONObject("planMap").getBigDecimal("rescPlanInte");

                AccountInfo accountInfo = new AccountInfo();
                accountInfo.setAmount(amount);
                accountInfo.setWaitIntrest(waitInterest);
                accountInfo.setTotalIntrest(totalInterest);
                return new CommonResponse(accountInfo);
            }
            return new CommonResponse(ResponseStatusEnum.QUERY_FAIL);

        } catch (Exception e) {
            return new CommonResponse(ResponseStatusEnum.QUERY_FAIL);
        }
    }
}
